<template>
  <el-main>
    <el-card>
      <!-- 更新页面标题样式 -->
      <div class="page-header">
        <div class="page-title">用户管理</div>
        <div class="page-subtitle">系统用户权限管理</div>
      </div>
      
      <div class="header-actions">
        <el-button v-if="isSuperAdmin" type="primary" @click="showAddDialog = true">添加用户</el-button>
        <div v-if="!isSuperAdmin" style="text-align: center; color: #666; margin-top: 10px;">
          <el-icon><InfoFilled /></el-icon>
          <span style="margin-left: 5px;">只有超级管理员可以添加新用户</span>
        </div>
      </div>
      
      <el-table :data="users" border stripe style="width:100%;">
        <el-table-column prop="username" label="用户名" width="160" />
        <el-table-column prop="role" label="角色" width="120">
          <template #default="scope">
            <el-select v-model="scope.row.role" @change="changeRole(scope.row)" :disabled="!isSuperAdmin && scope.row.role === 'superadmin'">
              <el-option label="普通用户" value="user" />
              <el-option label="管理员" value="admin" />
              <el-option v-if="isSuperAdmin" label="超级管理员" value="superadmin" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="needResetPwd" label="需改密" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.needResetPwd ? 'warning' : 'success'">
              {{ scope.row.needResetPwd ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="disabled" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.disabled ? 'danger' : 'success'">
              {{ scope.row.disabled ? '禁用' : '启用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="340">
          <template #default="scope">
            <el-button size="small" @click="resetPwd(scope.row)">重置密码</el-button>
            <el-button size="small" @click="toggleUser(scope.row)" :disabled="!isSuperAdmin && scope.row.role === 'superadmin'">{{ scope.row.disabled ? '启用' : '禁用' }}</el-button>
            <el-button size="small" type="danger" v-if="isAdmin && (isSuperAdmin || scope.row.role !== 'superadmin')" @click="deleteUser(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 18px 0; text-align: right;">
        <el-button type="primary" @click="showChangePwdDialog = true">修改我的密码</el-button>
      </div>
      <el-dialog v-model="showChangePwdDialog" title="修改我的密码" width="350px">
        <el-form :model="changePwdForm">
          <el-form-item label="旧密码">
            <el-input v-model="changePwdForm.oldPwd" type="password" placeholder="请输入旧密码" />
          </el-form-item>
          <el-form-item label="新密码">
            <el-input v-model="changePwdForm.newPwd" type="password" placeholder="请输入新密码" />
          </el-form-item>
          <el-form-item label="确认新密码">
            <el-input v-model="changePwdForm.confirm" type="password" placeholder="请再次输入新密码" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showChangePwdDialog = false">取消</el-button>
          <el-button type="primary" @click="changeMyPassword">修改</el-button>
        </template>
      </el-dialog>
      <el-dialog v-if="isSuperAdmin" v-model="showAddDialog" title="添加用户" width="400px">
        <el-form :model="addForm" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="addForm.username" placeholder="用户名（唯一）" />
          </el-form-item>
          <el-form-item label="初始密码">
            <el-input v-model="addForm.password" placeholder="初始密码" />
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="addForm.role">
              <el-option label="普通用户" value="user" />
              <el-option label="管理员" value="admin" />
              <el-option v-if="isSuperAdmin" label="超级管理员" value="superadmin" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="addUser">添加</el-button>
        </template>
        <div class="login-error" v-if="addError">{{ addError }}</div>
      </el-dialog>
    </el-card>
    <div style="margin-top: 32px; text-align: center;">
      <el-button type="danger" v-if="!isAdmin" @click="deleteMyAccount">注销我的账号</el-button>
    </div>
  </el-main>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import AV from '../leancloud'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
const users = ref([])
const showAddDialog = ref(false)
const addForm = ref({ username: '', password: '', role: 'user' })
const addError = ref('')
const showChangePwdDialog = ref(false)
const changePwdForm = ref({ oldPwd: '', newPwd: '', confirm: '' })
const isAdmin = localStorage.getItem('userRole') === 'admin' || localStorage.getItem('userRole') === 'superadmin'
const isSuperAdmin = localStorage.getItem('userRole') === 'superadmin'

// 查询所有UserProfile
async function fetchUsers() {
  const query = new AV.Query('UserProfile')
  query.limit(1000)
  const res = await query.find()
  users.value = res.map(u => ({
    objectId: u.id,
    username: u.get('username'),
    role: u.get('role') || 'user',
    needResetPwd: !!u.get('needChangePwd'),
    disabled: !u.get('isActive')
  }))
}
onMounted(fetchUsers)

// 添加用户：注册_User并新建UserProfile
async function addUser() {
  addError.value = ''
  
  // 权限检查：只有超级管理员可以添加用户
  if (!isSuperAdmin) {
    addError.value = '只有超级管理员可以添加用户'
    return
  }
  
  if (!addForm.value.username || !addForm.value.password) {
    addError.value = '用户名和初始密码不能为空'
    return
  }
  // 检查唯一
  if (users.value.some(u => u.username === addForm.value.username)) {
    addError.value = '用户名已存在'
    return
  }
  try {
    const user = new AV.User();
    user.setUsername(addForm.value.username);
    user.setPassword(addForm.value.password);
    await user.signUp();
    await user.fetch(); // 确保 user.id 有值
    
    // 新建UserProfile
    const profile = new AV.Object('UserProfile')
    profile.set('username', addForm.value.username)
    profile.set('role', addForm.value.role)
    profile.set('isActive', true)
    profile.set('needChangePwd', true)
    
    // 设置ACL权限
    const aclProfile = new AV.ACL()
    aclProfile.setPublicReadAccess(true)
    aclProfile.setPublicWriteAccess(false)
    aclProfile.setRoleWriteAccess('admin', true)
    aclProfile.setRoleWriteAccess('superadmin', true)
    profile.setACL(aclProfile)
    
    await profile.save()
    
    // 如果是管理员或超级管理员，确保角色存在并添加用户到该角色
    if (addForm.value.role === 'admin' || addForm.value.role === 'superadmin') {
      try {
        const roleName = addForm.value.role
        const role = new AV.Role(roleName, new AV.ACL())
        await role.save()
        role.getUsers().add(user)
        await role.save()
      } catch (roleError) {
        // 如果角色已存在，直接添加用户
        const roleQuery = new AV.Query(AV.Role)
        roleQuery.equalTo('name', addForm.value.role)
        const existingRole = await roleQuery.first()
        if (existingRole) {
          existingRole.getUsers().add(user)
          await existingRole.save()
        }
      }
    }
    
    ElMessage.success('用户添加成功')
    showAddDialog.value = false
    addForm.value = { username: '', password: '', role: 'user' }
    fetchUsers()
  } catch (e) {
    if (e.code === 202 || (e.code === 400 && e.message && e.message.includes('taken'))) {
      addError.value = '用户名已存在，请换一个！';
    } else {
      addError.value = e.message || '添加失败';
    }
  }
}
// 重置密码：只标记UserProfile
async function resetPwd(row) {
  try {
    const profile = AV.Object.createWithoutData('UserProfile', row.objectId)
    profile.set('needChangePwd', true)
    await profile.save()
    ElMessage.success('已标记为需重置密码')
    fetchUsers()
  } catch (e) {
    ElMessage.error('重置失败：' + (e.message || '未知错误'))
  }
}
// 角色变更
async function changeRole(row) {
  try {
    // 权限检查：只有超级管理员可以分配超级管理员角色
    if (row.role === 'superadmin' && !isSuperAdmin) {
      ElMessage.error('只有超级管理员可以分配超级管理员角色')
      return
    }
    
    const profile = AV.Object.createWithoutData('UserProfile', row.objectId)
    profile.set('role', row.role)
    await profile.save()
    ElMessage.success('角色已更新')
    fetchUsers()
  } catch (e) {
    ElMessage.error('修改失败：' + (e.message || '未知错误'))
  }
}
// 启用/禁用
async function toggleUser(row) {
  try {
    // 权限检查：只有超级管理员可以禁用/启用超级管理员
    if (row.role === 'superadmin' && !isSuperAdmin) {
      ElMessage.error('只有超级管理员可以禁用/启用超级管理员用户')
      return
    }
    
    const profile = AV.Object.createWithoutData('UserProfile', row.objectId)
    profile.set('isActive', !row.disabled)
    await profile.save()
    ElMessage.success(row.disabled ? '已启用' : '已禁用')
    fetchUsers()
  } catch (e) {
    ElMessage.error('操作失败：' + (e.message || '未知错误'))
  }
}
// 删除用户
async function deleteUser(row) {
  try {
    // 权限检查：只有超级管理员可以删除超级管理员
    if (row.role === 'superadmin' && !isSuperAdmin) {
      ElMessage.error('只有超级管理员可以删除超级管理员用户')
      return
    }
    
    // 只删除UserProfile
    await AV.Object.createWithoutData('UserProfile', row.objectId).destroy()
    ElMessage.success('用户档案已删除')
    fetchUsers()
  } catch (e) {
    ElMessage.error('删除失败：' + (e.message || '未知错误'))
  }
}

// 普通用户自助注销账号
async function deleteMyAccount() {
  try {
    // 删除自己的UserProfile
    const currentUser = AV.User.current()
    if (!currentUser) {
      ElMessage.error('未登录')
      return
    }
    // 查找自己的UserProfile
    const query = new AV.Query('UserProfile')
    query.equalTo('username', currentUser.getUsername())
    const profile = await query.first()
    if (profile) {
      await profile.destroy()
    }
    // 删除自己的_User
    await currentUser.destroy()
    ElMessage.success('账号已注销')
    setTimeout(() => { window.location.reload() }, 1000)
  } catch (e) {
    ElMessage.error('注销失败：' + (e.message || '未知错误'))
  }
}
// 普通用户自助修改密码
async function changeMyPassword() {
  if (!changePwdForm.value.oldPwd || !changePwdForm.value.newPwd || !changePwdForm.value.confirm) {
    ElMessage.error('请填写完整信息')
    return
  }
  if (changePwdForm.value.newPwd !== changePwdForm.value.confirm) {
    ElMessage.error('两次输入的新密码不一致')
    return
  }
  try {
    await AV.User.current().updatePassword(changePwdForm.value.oldPwd, changePwdForm.value.newPwd)
    ElMessage.success('密码修改成功，请重新登录')
    showChangePwdDialog.value = false
    // 可选：自动登出
    setTimeout(() => { window.location.reload() }, 1000)
  } catch (e) {
    if ([400, 210, 211, 1].includes(e.code)) {
      ElMessage.error('旧密码错误，请重新输入！')
    } else {
      ElMessage.error('修改失败：' + (e.message || '未知错误'))
    }
  }
}
</script>

<style scoped>
/* 页面标题样式 */
.page-header {
  margin-bottom: 20px;
  text-align: center;
}

/* 页面标题样式已移至全局样式文件 */

.header-actions {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

/* 统一按钮样式 */
.page-header .el-button {
  font-weight: 600;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 6px;
  gap: 6px;
  height: 36px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.page-header .el-button[type="primary"] {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: 1px solid #409eff;
  color: white;
}

.page-header .el-button[type="primary"]:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d5aa0 100%);
  border-color: #337ecc;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

/* 表格中的按钮样式 */
.el-table .el-button {
  font-weight: 600;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  gap: 4px;
  height: 28px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.el-table .el-button[type="danger"] {
  background: linear-gradient(135deg, #f56c6c 0%, #e74c3c 100%);
  border: 1px solid #f56c6c;
  color: white;
}

.el-table .el-button[type="danger"]:hover {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
  border-color: #e74c3c;
  transform: translateY(-1px);
  box-shadow: 0 3px 6px rgba(245, 108, 108, 0.3);
}

/* 对话框中的按钮样式 */
.el-dialog .el-button {
  font-weight: 600;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 6px;
  gap: 6px;
  height: 36px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.el-dialog .el-button[type="primary"] {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: 1px solid #409eff;
  color: white;
}

.el-dialog .el-button[type="primary"]:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d5aa0 100%);
  border-color: #337ecc;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.el-dialog .el-button[type="danger"] {
  background: linear-gradient(135deg, #f56c6c 0%, #e74c3c 100%);
  border: 1px solid #f56c6c;
  color: white;
}

.el-dialog .el-button[type="danger"]:hover {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
  border-color: #e74c3c;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(245, 108, 108, 0.3);
}

/* 确保按钮内容居中 */
.el-button .el-button__content {
  display: flex;
  justify-content: center;
  align-items: center;
}
.login-error {
  color: #d9001b;
  margin-top: 8px;
  text-align: center;
  font-size: 15px;
}
@media (max-width: 700px) {
  .el-main {
    padding: 4px !important;
  }
  .page-header {
    text-align: left;
    padding-left: 10px;
    padding-bottom: 5px;
  }
  /* 页面标题样式已移至全局样式文件 */
  .header-actions {
    justify-content: flex-start;
    padding-left: 10px;
  }
  .el-table {
    font-size: 13px;
    min-width: 600px;
    overflow-x: auto;
    display: block;
  }
  .el-table__body-wrapper {
    overflow-x: auto !important;
  }
  .el-button, .el-input, .el-select {
    font-size: 16px !important;
    min-height: 38px !important;
  }
  .el-dialog {
    width: 98vw !important;
    min-width: unset !important;
    max-width: 100vw !important;
    margin: 0 auto;
  }
  .el-form-item__label {
    font-size: 15px !important;
  }
}
</style> 